#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import os, time, random
from collections import OrderedDict
import json

import serial
import serial.tools.list_ports

from common.libs.Log import logging

from ui.axisSetDialog import Ui_Dialog

CONFIG_PATH = os.getcwd()+'/conf/axis.json'

class axisSetDialog(QDialog, Ui_Dialog):
    signal_name_changed = pyqtSignal(str, str)
    signal_pos_changed = pyqtSignal(str, str)
    signal_enable_changed = pyqtSignal(str, bool)

    signal_serial_changed = pyqtSignal(str, str)

    def __init__(self, parent=None, config=None, config_path=None):
        super(axisSetDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle('设置窗口')
        # self.setWindowState(Qt.WindowMaximized)
        # self.setMinimumHeight(300)
        # self.setMinimumWidth(450)

        self.pushButton_update_com.clicked.connect(self.serialUpdate)
        self.comboBox_com_port.currentIndexChanged.connect(self.serialChanged)
        self.comboBox_com_baud.currentIndexChanged.connect(self.serialChanged)

        self.pushButton_save.clicked.connect(self.accept)
        self.pushButton_cancel.clicked.connect(self.reject)

        self.readConfig()

        self.font = QFont()
        self.font.setFamily("Agency FB")
        self.font.setPointSize(28)
        font = self.font

        self.pushButton_cancel.setFont(font)
        self.pushButton_save.setFont(font)
        self.pushButton_update_com.setFont(font)
        self.comboBox_com_baud.setFont(font)
        self.comboBox_com_port.setFont(font)

        self.size = QSize(100, 100)
        size = self.size
        self.pushButton_cancel.setMinimumSize(size)
        self.pushButton_save.setMinimumSize(size)
        self.pushButton_update_com.setMinimumSize(size)
        self.comboBox_com_baud.setMinimumSize(size)
        self.comboBox_com_port.setMinimumSize(size)

        # ui加载
        self.uiLoad()

    def uiLoad(self):
        serial = self.config['serial']
        self.comboBox_com_port.addItems([serial['port']])
        for i in range(0,self.comboBox_com_baud.count()):
            if self.comboBox_com_baud.itemText(i) == serial['baud']:
                self.comboBox_com_baud.setCurrentIndex(i)
                break

        self.lineEdit_name_dict = {}
        self.lineEdit_pos_dict = {}
        self.checkBox_enable_dict = {}
        i = 0
        size = self.size
        font = self.font
        axis = self.config['axis']
        for k in axis:
            # 获取信息
            item = axis[k]
            name = item['name'] if 'name' in item else ''
            pos = item['pos'] if 'pos' in item else ''
            enable = int(item['enable']) if 'enable' in item else 0
            # 创建控件
            label_name = QLabel("名称:")
            label_name.setFont(font)
            label_pos = QLabel("点位")
            label_pos.setFont(font)
            lineEdit_name = QLineEdit(name)
            lineEdit_name.textChanged.connect(self.textChangedName)
            lineEdit_name.setMinimumSize(size)
            lineEdit_name.setFont(font)
            lineEdit_pos = QLineEdit(pos)
            lineEdit_pos.textChanged.connect(self.textChangedPos)
            lineEdit_pos.setMinimumSize(size)
            lineEdit_pos.setFont(font)
            checkBox_enable = QCheckBox("启用")
            checkBox_enable.setCheckState(enable)
            checkBox_enable.setTristate(False)
            checkBox_enable.stateChanged.connect(self.stateChangedEnable)
            checkBox_enable.setMinimumSize(size)
            checkBox_enable.setFont(font)
            # 添加控件
            self.gridLayout_axis.addWidget(label_name, i, 0, 1, 1)
            self.gridLayout_axis.addWidget(lineEdit_name, i, 1, 1, 1)
            self.gridLayout_axis.addWidget(label_pos, i, 2, 1, 1)
            self.gridLayout_axis.addWidget(lineEdit_pos, i, 3, 1, 1)
            # self.gridLayout_axis.addWidget(checkBox_enable, i, 4, 1, 1)
            # 保存控件
            self.lineEdit_name_dict[k] = lineEdit_name
            self.lineEdit_pos_dict[k] = lineEdit_pos
            self.checkBox_enable_dict[k] = checkBox_enable
            i += 1

    def accept(self):
        if self.writeConfig():
            QDialog.accept(self)

    # def reject(self):
    #     QDialog.reject(self)

    def serialChanged(self):
        self.signal_serial_changed.emit(self.comboBox_com_port.currentText(), self.comboBox_com_baud.currentText())
    
    def serialUpdate(self):
        com_list = []
        port_list = serial.tools.list_ports.comports()
        for p in port_list:
            port = p.device
            com_list.append(port)
        self.comboBox_com_port.clear()
        self.comboBox_com_port.addItems(com_list)

    def writeConfig(self):
        """写入配置文件"""
        try:
            # 保存串口信息
            serial = self.config['serial']
            serial['port'] = self.comboBox_com_port.currentText()
            serial['baud'] = self.comboBox_com_baud.currentText()
            self.config['serial'] = serial
            # 保存坐标信息
            axis = self.config['axis']
            for k in axis:
                axis[k]['name'] = str(self.lineEdit_name_dict[k].text())
                axis[k]['pos'] = str(self.lineEdit_pos_dict[k].text())
            self.config['axis'] = axis

            save = json.dumps(self.config, indent=4)
            with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
                f.write(save)
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
            return True
        except Exception as e:
            logging.info(e)
            QMessageBox.information(self,"提示","保存失败, 文件被调用", QMessageBox.Yes)
            return False


    def readConfig(self):
        """读取配置文件"""
        with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
            self.config = json.loads(f.read(), object_pairs_hook=OrderedDict)
            
    def textChangedName(self, txt): 
        obj = self.sender() # 获取发射信号的对象
        for k in self.lineEdit_name_dict:
            if self.lineEdit_name_dict[k] == obj:
                self.signal_name_changed.emit(k, txt)
                break

    def textChangedPos(self, txt): 
        obj = self.sender() # 获取发射信号的对象
        for k in self.lineEdit_pos_dict:
            if self.lineEdit_pos_dict[k] == obj:
                self.signal_pos_changed.emit(k, txt)
                break

    def stateChangedEnable(self, state): 
        obj = self.sender() # 获取发射信号的对象
        for k in self.checkBox_enable_dict:
            if self.checkBox_enable_dict[k] == obj:
                self.signal_enable_changed.emit(k, state)
                break

